import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/topic/data/count_model.dart';
import 'package:flutter_learn_vi/src/page/topic/data/topic_text_model.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_details_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_drawer_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_two_select_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';
import 'package:provider/provider.dart';

import '../../bean/bean_problem.dart';
import '../../utils/navigator_utils.dart';
import 'controller/question_error_controller.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/12.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///答题主页面
class TopicSelectPage extends StatefulWidget {
  final String pageTitle;
  final String categoryOne;
  final int taskId;

  TopicSelectPage({this.pageTitle, this.taskId, @required this.categoryOne});

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TopicSelectPage> {
  @override
  void initState() {
    super.initState();
    Get.put(AuestionErrorController());
    Future.delayed(Duration.zero, () {
      context.read<TopicTextModel>().init();
      context.read<CountModel>().init();
    });
    getCategorys();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,

      appBar: AppBar(
        title: Text("${widget.pageTitle}"),
        centerTitle: true,
        actions: [
          GetBuilder(
            builder: (AuestionErrorController controller) {
              List<ProblemModel> requestList = controller.requestList;
              if (requestList.length == 0) {
                return SizedBox();
              }
              return Builder(builder: (BuildContext context) {
                return TextButton(
                    onPressed: () {
                      Scaffold.of(context).openEndDrawer();
                    },
                    child: Container(
                        width: 40,
                        padding: EdgeInsets.all(8),
                        child:
                            Image.asset("assets/images/2.0x/mulu_icon.png")));
              });
            },
          ),
          GestureDetector(
            onTap: () {
              context.read<TopicTextModel>().addTextSize();
            },
            child: Container(
                width: 40,
                padding: EdgeInsets.all(6),
                child: Image.asset("assets/images/2.0x/放大.png")),
          ),
          GestureDetector(
            onTap: () {
              context.read<TopicTextModel>().subtractTextSize();
            },
            child: Container(
                width: 40,
                padding: EdgeInsets.all(8),
                margin: EdgeInsets.only(right: 10),
                child: Image.asset("assets/images/2.0x/缩小.png")),
          )
        ],
      ),
      backgroundColor: Colors.white,
      endDrawer: GetBuilder(
        builder: (AuestionErrorController controller) {
          return buildEndDrawer();
        },
      ),

      ///填充布局
      body: buildBody(),
    );
  }

  List<CategoryBean> _categoryList = [];

  bool isLevel = false;
  bool isFinish = false;

  Future<bool> getCategorys() async {
    Map<String, dynamic> map = Map();
    map["categoryOneCode"] = widget.categoryOne;

    isFinish = false;
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.categorysTwo,
      queryParameters: map,
    );

    isFinish = true;
    _categoryList = [];
    if (responseInfo.success) {
      List list = responseInfo.data;
      list.forEach((element) {
        CategoryBean newsBean = CategoryBean.fromJson(element);
        _categoryList.add(newsBean);
      });
    } else {
      ToastUtils.showToast("${responseInfo.message}");
      if (responseInfo.code == 401) {
      } else {
        NavigatorUtils.pop(context);
      }
      return false;
    }

    if (_categoryList.length > 1) {
      LogUtils.e("有二级页面");
      int isCheck = UserHelper.getInstance.userBean.isCheck;
      LogUtils.e("有二级页面 $isCheck");
      if (isCheck == 1) {
        isLevel = false;
      } else {
        isLevel = true;
      }
    } else {
      LogUtils.e("无二级页面");
      isLevel = false;
    }

    setState(() {});

    return Future.value(true);
  }

  buildBody() {
    if (_categoryList.length == 0) {
      if (isFinish) {
        return Center(
          child: NoDataWidget(
            clickCallBack: () {
              getCategorys();
            },
          ),
        );
      }
      return Center(
        child: LoadingWidget(),
      );
    }

    if (isLevel) {
      //二级选择
      return TopicSelectTwoPage(
        categoryOne: widget.categoryOne,
        categoryList: _categoryList,
        pageTitle: widget.pageTitle,
      );
    } else {
      //抽题页面
      return TopicDetilsPage(
        taskId: widget.taskId,
        themTitle: widget.pageTitle,
        categoryOne: widget.categoryOne,
        categoryTwo: _categoryList[0].categoryCode,
      );
    }
  }

  Widget buildEndDrawer() {
    return TopicDrawerPage();
  }
}
